package com.wfs.suanfa.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

public class CasABADemoStamp {

    public static void main(final String[] args) {
       final AtomicStampedReference<Integer> a=new AtomicStampedReference(1,0);

        Thread mian=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("操作线程:"+Thread.currentThread().getName()+",初始值:"+a.getReference());
                Integer expectReference=a.getReference();
                Integer newReference=expectReference+1;
                Integer expectStamp=a.getStamp();
                Integer newexpectStamp=expectStamp+1;
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean isCASSccuess=a.compareAndSet(expectReference,newReference,expectStamp,newexpectStamp);
                System.out.println("操作线程:"+Thread.currentThread().getName()+",CAS操作:"+isCASSccuess);
            }
        },"主线程");

        Thread other=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100L);
                    a.compareAndSet(a.getReference(),a.getReference()+1,a.getStamp(),a.getStamp() +1);//加1

                    System.out.println("操作线程:"+Thread.currentThread().getName()+",increment:"+a.getReference());
                    a.compareAndSet(a.getReference(),a.getReference()-1,a.getStamp(),a.getStamp() +1);//加1;//减一
                    System.out.println("操作线程:"+Thread.currentThread().getName()+",increment:"+a.getReference());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"干扰线程");
        mian.start();
        other.start();
    }
}
